<template>
  <div class="novel-list">
    <div class="operation-bar">
      <a-button type="primary" @click="showAddModal">新增小说</a-button>
      <a-input-search
        v-model="searchQuery"
        placeholder="搜索小说名称"
        style="width: 200px; margin-left: 16px"
        @search="onSearch"
      />
    </div>

    <a-table
      :columns="columns"
      :data-source="novelList"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #cover="{ text }">
        <img :src="text" alt="封面" style="width: 50px; height: 70px" />
      </template>
      
      <template #action="{ record }">
        <a-space>
          <a @click="handleEdit(record)">编辑</a>
          <a @click="handleChapterManage(record)">章节管理</a>
          <a-popconfirm
            title="确定要删除这本小说吗？"
            @confirm="handleDelete(record.id)"
          >
            <a>删除</a>
          </a-popconfirm>
        </a-space>
      </template>
    </a-table>

    <!-- 新增/编辑弹窗 -->
    <a-modal
      :title="modalTitle"
      :visible="modalVisible"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form :form="form">
        <a-form-item label="小说名称">
          <a-input
            v-decorator="[
              'name',
              { rules: [{ required: true, message: '请输入小说名称' }] }
            ]"
          />
        </a-form-item>
        <a-form-item label="作者">
          <a-select
            v-decorator="[
              'authorId',
              { rules: [{ required: true, message: '请选择作者' }] }
            ]"
          >
            <a-select-option v-for="author in authors" :key="author.id" :value="author.id">
              {{ author.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="分类">
          <a-select
            v-decorator="[
              'categoryId',
              { rules: [{ required: true, message: '请选择分类' }] }
            ]"
          >
            <a-select-option v-for="category in categories" :key="category.id" :value="category.id">
              {{ category.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-decorator="[
              'status',
              { rules: [{ required: true, message: '请选择状态' }] }
            ]"
          >
            <a-select-option value="serializing">连载中</a-select-option>
            <a-select-option value="completed">已完结</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="简介">
          <a-textarea
            v-decorator="[
              'description',
              { rules: [{ required: true, message: '请输入简介' }] }
            ]"
            :rows="4"
          />
        </a-form-item>
        <a-form-item label="封面">
          <a-upload
            name="cover"
            list-type="picture-card"
            :show-upload-list="false"
            :before-upload="beforeUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" alt="封面" />
            <div v-else>
              <a-icon type="plus" />
              <div class="ant-upload-text">上传封面</div>
            </div>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import formValidation from '@/mixins/formValidation'

export default {
  name: 'NovelList',
  mixins: [formValidation],
  data() {
    return {
      loading: false,
      searchQuery: '',
      modalVisible: false,
      modalTitle: '新增小说',
      imageUrl: '',
      form: this.$form.createForm(this),
      columns: [
        {
          title: '封面',
          dataIndex: 'cover',
          scopedSlots: { customRender: 'cover' }
        },
        {
          title: '小说名称',
          dataIndex: 'name',
          sorter: true
        },
        {
          title: '作者',
          dataIndex: 'authorName'
        },
        {
          title: '分类',
          dataIndex: 'categoryName'
        },
        {
          title: '状态',
          dataIndex: 'status',
          customRender: (text) => {
            const status = {
              serializing: '连载中',
              completed: '已完结'
            }
            return status[text]
          }
        },
        {
          title: '字数',
          dataIndex: 'wordCount',
          sorter: true
        },
        {
          title: '更新时间',
          dataIndex: 'updateTime',
          sorter: true
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'action' }
        }
      ],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      novelList: [],
      authors: [],
      categories: []
    }
  },
  created() {
    this.fetchNovelList()
    this.fetchAuthors()
    this.fetchCategories()
  },
  methods: {
    async fetchNovelList() {
      this.loading = true
      try {
        // TODO: 调用API获取小说列表
        // const res = await this.$api.novel.getList({
        //   page: this.pagination.current,
        //   pageSize: this.pagination.pageSize,
        //   query: this.searchQuery
        // })
        // this.novelList = res.data.list
        // this.pagination.total = res.data.total
      } catch (error) {
        this.$message.error('获取小说列表失败')
      }
      this.loading = false
    },
    async fetchAuthors() {
      // TODO: 获取作者列表
    },
    async fetchCategories() {
      // TODO: 获取分类列表
    },
    showAddModal() {
      this.modalTitle = '新增小说'
      this.modalVisible = true
      this.imageUrl = ''
      this.form.resetFields()
    },
    handleEdit(record) {
      this.modalTitle = '编辑小说'
      this.modalVisible = true
      this.imageUrl = record.cover
      this.$nextTick(() => {
        this.form.setFieldsValue({
          name: record.name,
          authorId: record.authorId,
          categoryId: record.categoryId,
          status: record.status,
          description: record.description
        })
      })
    },
    async handleModalOk() {
      try {
        const values = await new Promise((resolve, reject) => {
          this.form.validateFields((errors, values) => {
            if (errors) {
              reject(errors)
            } else {
              resolve(values)
            }
          })
        })
        
        // TODO: 调用API保存数据
        this.modalVisible = false
        this.fetchNovelList()
      } catch (error) {
        // 表单验证失败
      }
    },
    handleModalCancel() {
      this.modalVisible = false
    },
    async handleDelete(id) {
      try {
        // TODO: 调用API删除小说
        this.$message.success('删除成功')
        this.fetchNovelList()
      } catch (error) {
        this.$message.error('删除失败')
      }
    },
    handleChapterManage(record) {
      this.$router.push(`/novel/chapter/${record.id}`)
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = pagination
      this.fetchNovelList()
    },
    onSearch() {
      this.pagination.current = 1
      this.fetchNovelList()
    },
    beforeUpload(file) {
      // TODO: 处理图片上传
      return false
    }
  }
}
</script>

<style lang="scss" scoped>
.novel-list {
  padding: 24px;
  
  .operation-bar {
    margin-bottom: 16px;
  }
}
</style> 